package com.sc.nft.consume;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.sc.nft.dao.UserInfoDao;
import com.sc.nft.entity.UserInfo;
import com.sc.nft.enums.AppTypeEnum;
import com.sc.nft.enums.MessageTopic;
import javax.annotation.Resource;

import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.enums.RegisterUserTagsEnum;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.UserInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@RocketMQMessageListener(topic = MessageTopic.USER_REGISTER_INIT+"${spring.profiles.active}" , consumerGroup = MessageTopic.USER_REGISTER_INIT+"${spring.profiles.active}" )
@Component
@Slf4j
@RequiredArgsConstructor
public class RegisterInitConsumer implements RocketMQListener<UserInfo> {

    @Resource
    private UserInfoService userInfoService;

    private final Redisson redisson;

    @Override
    public void onMessage(UserInfo userInfo) {

        String key = RedisKeyEnum.USER_REGISTER_INIT_LOCK.getKey() + userInfo.getId();

        RLock lock = redisson.getLock(key);
        try {
            boolean res = lock.tryLock(30,  TimeUnit.SECONDS);
          if (res) {
            userInfoService.initUserWalletAndAddr(userInfo);
            }else{
              log.error("未获取到锁:{}",userInfo.getId());
              return;
          }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new GlobalRunTimeException("系统超时");
        } finally {
            lock.unlock();
        }


    }

}
